/**
 * 博客数据 Store
 *
 * 基于 Axios 的数据管理：
 * - 使用简化的 API 结构
 * - Store 不处理异常，异常在组件中处理
 * - 简化数据流处理
 */
import { defineStore } from 'pinia'
import type {
  Article,
  ArticleQueryParams,
  ArticleListResponse,
  SearchResponse,
  Pagination,
  ID,
  ArticleSearchParams,
} from '@/types/blog.types'
import { blogApis } from '@/apis'
import {
  handlePaginatedApiResponse,
  handleApiResponse,
  isApiSuccess,
  getApiErrorMessage,
} from '@/utils/api-response'

// Store 状态接口定义
interface BlogStoreState {
  articles: Article[]
  currentArticle: Article | null
  searchResults: Article[]

  // 分页信息
  pagination: Pagination
  searchPagination: Pagination

  // 加载状态
  loading: boolean
  articlesLoading: boolean
  searchLoading: boolean
}

export const useBlogStore = defineStore('blog', {
  state: (): BlogStoreState => ({
    // 数据状态
    articles: [],
    currentArticle: null,
    searchResults: [],

    // 分页信息
    pagination: {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0,
      hasNext: false,
      hasPrev: false,
    },
    searchPagination: {
      page: 1,
      limit: 10,
      total: 0,
      totalPages: 0,
      hasNext: false,
      hasPrev: false,
    },

    // 加载状态
    loading: false,
    articlesLoading: false,
    searchLoading: false,
  }),

  getters: {
    // 特色文章（前3篇）
    featuredArticles: (state): Article[] => state.articles.slice(0, 3),

    // 最新文章（前5篇）
    recentArticles: (state): Article[] => state.articles.slice(0, 5),

    // 任何加载状态
    isAnyLoading: (state): boolean => state.loading || state.articlesLoading || state.searchLoading,
  },

  actions: {
    /**
     * 获取文章列表
     */
    async fetchArticles(params: ArticleQueryParams = { page: 1, limit: 10 }) {
      this.articlesLoading = true
      try {
        const response = await blogApis.article.getArticles(params)
        const apiResponse = handlePaginatedApiResponse(response)

        if (isApiSuccess(apiResponse)) {
          this.articles = apiResponse.data
          this.pagination = apiResponse.pagination
        } else {
          console.error('获取文章失败:', getApiErrorMessage(apiResponse))
          this.articles = []
        }
      } catch (error) {
        console.error('获取文章失败:', error)
        this.articles = []
      } finally {
        this.articlesLoading = false
      }
    },

    /**
     * 获取单篇文章（通过ID）
     */
    async fetchArticle(id: string) {
      this.loading = true
      try {
        const response = await blogApis.article.getArticle(id)
        const apiResponse = handleApiResponse(response)

        if (isApiSuccess(apiResponse)) {
          this.currentArticle = apiResponse.data
        } else {
          console.error('获取文章失败:', getApiErrorMessage(apiResponse))
          this.currentArticle = null
        }
      } catch (error) {
        console.error('获取文章失败:', error)
        this.currentArticle = null
      } finally {
        this.loading = false
      }
    },

    /**
     * 根据 slug 获取文章（别名方法）
     */
    async fetchArticleBySlug(slug: string) {
      this.loading = true
      try {
        const response = await blogApis.article.getArticleBySlug(slug)
        const apiResponse = handleApiResponse(response)

        if (isApiSuccess(apiResponse)) {
          this.currentArticle = apiResponse.data
        } else {
          console.error('获取文章失败:', getApiErrorMessage(apiResponse))
          this.currentArticle = null
        }
      } catch (error) {
        console.error('获取文章失败:', error)
        this.currentArticle = null
      } finally {
        this.loading = false
      }
    },

    /**
     * 初始化数据（首页需要的数据）
     */
    async initializeData() {
      this.loading = true

      // 获取基础数据
      await this.fetchArticles({ page: 1, limit: 20 })

      this.loading = false
    },

    /**
     * 清空搜索结果
     */
    clearSearchResults() {
      this.searchResults = []
      this.searchPagination = {
        page: 1,
        limit: 10,
        total: 0,
        totalPages: 0,
        hasNext: false,
        hasPrev: false,
      }
    },

    /**
     * 重置当前文章
     */
    clearCurrentArticle() {
      this.currentArticle = null
    },
  },
})
